import numpy as np
import pandas as pd
from sklearn import datasets, linear_model
import matplotlib.pyplot as plt


# 读取数据函数
def get_data(file_name):
    data = pd.read_csv(file_name)  # 读取cvs文件
    x_parameter = []
    y_parameter = []
    for single_square_feet, single_price_value in zip(data['square_feet'], data['price']):
        # 遍历数据
        x_parameter.append([float(single_square_feet)])  # 存储在相应的list列表中
        y_parameter.append(float(single_price_value))
    return x_parameter, y_parameter


# 将数据拟合到线性模型
def linear_model_main(x_parameters, y_parameters, predict_value):
    regr = linear_model.LinearRegression()
    regr.fit(x_parameters, y_parameters)  # 训练模型
    predict_outcome = regr.predict(predict_value)
    predictions = {'intercept': regr.intercept_, 'coefficient': regr.coef_, 'predicted_value': predict_outcome}
    return predictions


# 显示线性拟合模型的结果
def show_linear_line(x_parameters, y_parameters):
    regr = linear_model.LinearRegression()
    regr.fit(x_parameters, y_parameters)
    plt.scatter(x_parameters, y_parameters, color='blue')
    plt.plot(x_parameters, regr.predict(x_parameters), color='red', linewidth=4)
    plt.xticks(())
    plt.yticks(())
    plt.show()


x, y = get_data('input_data.csv')
predictValue = [[700]]
result = linear_model_main(x, y, predictValue)
print("Intercept value", result['intercept'])
print("coefficient", result['coefficient'])
print("Predicted value", result['predicted_value'])
show_linear_line(x, y)

import pandas as pd
data=pd.read_csv("D:/Data/Advertising.csv")
print(data.head())

import pandas as pd
data=pd.read_csv("D:/Data/Advertising.csv")
print(data.tail())

import pandas as pd
data=pd.read_csv("D:/Data/Advertising.csv")
print(data.shape)


import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = pd.read_csv("D:/Data/Advertising.csv")
#  使用散点图可视化特征与相应之间的关系
sns.pairplot(data, x_vars=['TV', 'radio', 'newspaper'], y_vars='sales', size=7, aspect=0.8,kind='reg')
plt.show()
#  这里选择TV.Radio.Newspaper作为特征，Sales作为观测值
import pandas as pd


data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols=['TV','radio','newspaper']
x=data[featrue_cols]
print(x.head())

import pandas as pd


data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols=['TV','radio','newspaper']
x=data[featrue_cols]
y=data['sales']
print(y.head())

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import numpy as np

data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols = ['TV', 'radio', 'newspaper']
x = data[featrue_cols]
y = data['sales']
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
print(x_train.shape)
print(x_test.shape)
print(y_train.shape)
print(y_test.shape)



import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import numpy as np

data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols = ['TV', 'radio', 'newspaper']
x = data[featrue_cols]
y = data['sales']
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
linreg = LinearRegression()
model = linreg.fit(x_train, y_train)
print(model)
print(linreg.intercept_)
print(linreg.coef_)

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import numpy as np

data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols = ['TV', 'radio', 'newspaper']
x = data[featrue_cols]
y = data['sales']
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
linreg = LinearRegression()
model = linreg.fit(x_train, y_train)
y_pred=linreg.predict(x_test)
print(y_pred)
print(type(y_pred))

print(type(y_pred),type(y_test))
print(len(y_pred),len(y_test))
print(y_pred.shape,y_test.shape)
sum_mean=0
for i in range(len(y_pred)):
    sum_mean+=(y_pred[i]-y_test.values[i])**2
sum_erro=np.sqrt(sum_mean/50)
print("RMSE by hand:",sum_erro)

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
import numpy as np

data = pd.read_csv("D:/Data/Advertising.csv")
featrue_cols = ['TV', 'radio', 'newspaper']
x = data[featrue_cols]
y = data['sales']
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
linreg = LinearRegression()
model = linreg.fit(x_train, y_train)
y_pred=linreg.predict(x_test)
sum_mean=0
for i in range(len(y_pred)):
    sum_mean+=(y_pred[i]-y_test.values[i])**2
sum_erro=np.sqrt(sum_mean/50)
plt.figure()
plt.plot(range(len(y_pred)),y_pred,'b',label="predict")
plt.plot(range(len(y_pred)),y_test,'r',label="test")
plt.legend(loc="upper right")
plt.xlabel("the number of sales")
plt.ylabel("value of sales")
plt.show()

